/*
 * @Author: silence
 * @Date: 2022-07-26 16:15:12
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-08-01 15:41:11
 * @Description: 网络参数拦截器：处理公共参数
 */
import 'package:dio/dio.dart';
import 'package:sp_util/sp_util.dart';
import '../config/AppInfo.dart';
import '../utils/Tool/MyTools.dart';
import '../utils/userbloc/user_bloc.dart';
import 'ApiUtils.dart';
import 'RequestParamsUtils.dart';

class NetParamInterceptor implements Interceptor {
  // 是否需要处理参数，默认需要处理
  final bool isNeedHandler;

  // 是否是表单
  final bool isFormData;

  const NetParamInterceptor(
      {this.isNeedHandler = true, this.isFormData = false});

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    handler.next(err);
  }

  @override
  Future<void> onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    // 如果需要处理参数，就在这里处理公共参数
    Map<String, dynamic>? headers = options.headers; // header参数
    dynamic? body = options.data; // body参数

    if (this.isNeedHandler) {
      if (body == null) body = Map(); // 处理参数为空的情况

      headers = {'Appid': AppId};

      //如果有凭证，就用凭证，否则用AppKey
      String? auth = await UserBlocTool.getUserAuth();
      if (MyTools.stringIsEmpty(auth)) {
         // headers['Authorization'] = AppKey;
      } else {
        headers['Authorization'] = auth;
      }

      // 处理公共参数body参数
      body = await getRequestEncryptionParamDictByParamDictType4(body, AppKey);
    }

    RequestOptions tempOptions = options;
    options.headers = headers;
    if (isFormData) {
      options.queryParameters = body as Map<String, dynamic>;
    }
    tempOptions.data = isFormData ? FormData.fromMap(body) : body; // 处理上传文件
    handler.next(tempOptions);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    handler.next(response);
  }
}
